﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Data.SqlClient;
using CNCSoft.EData;

using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.Controls;

using Common;

namespace CNCSoft.ErpApps.TMS.Counsellor
{
    
    public partial class frmDuyetTuyenSinh : Form
    {

        private SqlDataAdapter dataAdapter = new SqlDataAdapter();
        DataSet ds = new DataSet();

        public frmDuyetTuyenSinh()
        {
            InitializeComponent();
        }

        private void frmDuyetTuyenSinh_Load(object sender, EventArgs e)
        {
            GetDSXetTuyen(true);
            bandedGridView1.IndicatorWidth = 35;  //Kich thuoc tieu de hang

            //Filter theo nam hoc default
            bandedGridView1.ActiveFilterString = "MaNienHoc = '" + GlobalVariable.WSInfo.getAppProperty("MaNienHocDefault","") + "'";
        }

        private void GetDSXetTuyen(bool bFirst)
        {
            try
            {
                
                if (ds.Tables["TUYENSINH_CHITIET"] != null)
                    ds.Tables["TUYENSINH_CHITIET"].Clear();
                if (ds.Tables["TUYENSINH_HOSOTUYENSINH"] != null)
                    ds.Tables["TUYENSINH_HOSOTUYENSINH"].Clear();
                if (ds.Tables["TUYENSINH"] != null)
                    ds.Tables["TUYENSINH"].Clear();

                dataAdapter = new SqlDataAdapter("SELECT MaTuyenSinh, HoLot + ' ' + Ten as HoTen, case gioitinh when 1 then N'Nam' else N'Nữ' end as GioiTinh, MaKhoiDangKy, TenCheDo, MaCoSo, " +
                                                 "NgayNopHoSo, NgayDuyet, NguoiDuyet, MaKetQuaXetTuyen, CoSoTiepNhan, LyDoXetDuyet, " +
                                                 "MaTrangThaiXetTuyen, HanDangKy, SoDienThoai, NhanVienTiepNhan, GhiChu, NhanVienNhanHoSo, MaNienHoc " + 
                                                 "FROM TUYENSINH M " + 
                                                 "LEFT JOIN DM_CHEDO ON M.MaCheDo = DM_CHEDO.MaCheDo "
                                                 ,GlobalVariable.WSInfo.ConnectionString);

                dataAdapter.Fill(ds, "TUYENSINH");

                dataAdapter = new SqlDataAdapter("SELECT ID, MaTuyenSinh, NoiDung, TenTruong, TenTinhTP, DiemToan, DiemLy, DiemHoa, DiemVan, DiemAnh, DiemSinh, MaHocLuc, MaHanhKiem " + 
                                                 "FROM TUYENSINH_CHITIET D " +
                                                 "LEFT JOIN DM_TRUONG ON D.MaTruong = DM_Truong.MaTruong " + 
                                                 "LEFT JOIN DM_TINHTP ON DM_TRUONG.MaTinhTP = DM_TINHTP.MaTinhTP", 
                                                GlobalVariable.WSInfo.ConnectionString);
                dataAdapter.Fill(ds, "TUYENSINH_CHITIET");
                
                dataAdapter = new SqlDataAdapter(@"select MaTuyenSinh, TenHoSo from TUYENSINH_HOSOTUYENSINH tshs
                                                inner join DM_HOSOTUYENSINH dmhs on dmhs.ID = tshs.MaHoSoTuyenSinh", GlobalVariable.WSInfo.ConnectionString);
                dataAdapter.Fill(ds, "TUYENSINH_HOSOTUYENSINH");
                

                if (bFirst)
                {
                    ds.Tables["TUYENSINH"].PrimaryKey = new DataColumn[] { ds.Tables["TUYENSINH"].Columns["MaTuyenSinh"] };
                    ds.Tables["TUYENSINH_CHITIET"].PrimaryKey = new DataColumn[] { ds.Tables["TUYENSINH_CHITIET"].Columns["ID"] };
                    ds.Tables["TUYENSINH_HOSOTUYENSINH"].PrimaryKey = new DataColumn[] { ds.Tables["TUYENSINH_HOSOTUYENSINH"].Columns["ID"] };

                    // Set relations
                    ds.Relations.Add("M_D", ds.Tables["TUYENSINH"].Columns["MaTuyenSinh"],
                        ds.Tables["TUYENSINH_CHITIET"].Columns["MaTuyenSinh"]);
                    ds.Relations.Add("M_H", ds.Tables["TUYENSINH"].Columns["MaTuyenSinh"],
                                    ds.Tables["TUYENSINH_HOSOTUYENSINH"].Columns["MaTuyenSinh"]);
                }

                grid_DSXetTuyen.DataSource = ds;
                grid_DSXetTuyen.DataMember = "TUYENSINH";

                grid_ThongTinXetTuyen.DataSource = ds;
                grid_ThongTinXetTuyen.DataMember = "TUYENSINH.M_D";

                gridControl_HoSoTuyenSinh.DataSource = ds;
                gridControl_HoSoTuyenSinh.DataMember = "TUYENSINH.M_H";

                
                if (ds.Tables["DM_KETQUAXETTUYEN"] != null)
                    ds.Tables["DM_KETQUAXETTUYEN"].Clear();
                dataAdapter = new SqlDataAdapter("SELECT * FROM DM_KETQUAXETTUYEN",GlobalVariable.WSInfo.ConnectionString);
                dataAdapter.Fill(ds, "DM_KETQUAXETTUYEN");
                repositoryItemLookUpEdit_KetQuaXetTuyen.DataSource = ds.Tables["DM_KETQUAXETTUYEN"];

                if (ds.Tables["DM_TRANGTHAIXETTUYEN"] != null)
                    ds.Tables["DM_TRANGTHAIXETTUYEN"].Clear();
                dataAdapter = new SqlDataAdapter("SELECT * FROM DM_TRANGTHAIXETTUYEN",GlobalVariable.WSInfo.ConnectionString);
                dataAdapter.Fill(ds, "DM_TRANGTHAIXETTUYEN");
                repositoryItemLookUpEdit_TrangThaiXetTuyen.DataSource = ds.Tables["DM_TRANGTHAIXETTUYEN"];

                bandedGridView1.BestFitColumns();

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: \n" + ex.StackTrace);
            }

        }

        private void bandedGridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {

        }

        private void cmdUpDate_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection cnn = new SqlConnection(GlobalVariable.WSInfo.ConnectionString);

                string sqlUpdate = "UPDATE TUYENSINH SET MaKetQuaXetTuyen = @pMaKetQuaXetTuyen, NguoiDuyet = @pNguoiDuyet, NgayDuyet = @pNgayDuyet,  " +
                                   "CoSoTiepNhan = @pCoSoTiepNhan, LyDoXetDuyet = @pLyDoXetDuyet, MaTrangThaiXetTuyen = @pMaTrangThaiXetTuyen, HanDangKy = @pHanDangKy " + 
                                   "WHERE MaTuyenSinh = @pMaTuyenSinh";

                SqlParameter[] pUpdate = new SqlParameter[8];

                pUpdate[0] = new SqlParameter("@pMaKetQuaXetTuyen", SqlDbType.NVarChar, 20, "MaKetQuaXetTuyen");
                pUpdate[1] = new SqlParameter("@pNguoiDuyet", SqlDbType.VarChar, 20, "NguoiDuyet");
                pUpdate[2] = new SqlParameter("@pNgayDuyet", SqlDbType.Date, 10, "NgayDuyet");
                pUpdate[3] = new SqlParameter("@pCoSoTiepNhan", SqlDbType.VarChar, 10, "CoSoTiepNhan");
                pUpdate[4] = new SqlParameter("@pLyDoXetDuyet", SqlDbType.NVarChar, 100, "LyDoXetDuyet");
                pUpdate[5] = new SqlParameter("@pMaTrangThaiXetTuyen", SqlDbType.VarChar, 2, "MaTrangThaiXetTuyen");
                pUpdate[6] = new SqlParameter("@pHanDangKy", SqlDbType.Date, 10, "HanDangKy");

                pUpdate[7] = new SqlParameter("@pMaTuyenSinh", SqlDbType.VarChar, 20, "MaTuyenSinh");

                SqlCommand cmdUpdate = new SqlCommand(sqlUpdate, cnn);
                cmdUpdate.Parameters.AddRange(pUpdate);

                dataAdapter.UpdateCommand = cmdUpdate;
                try
                {
                    dataAdapter.Update(ds, "TUYENSINH");
                    ds.AcceptChanges();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            //GetDSXetTuyen(false);
            ds.RejectChanges();
        }

        private void bandedGridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle > -1)
                e.Info.DisplayText = (e.RowHandle+1).ToString();
        }

        private void cmdInGBTN_Click(object sender, EventArgs e)
        {
            if (!((ds.Tables["TUYENSINH"].Rows[bandedGridView1.FocusedRowHandle]["MaKetQuaXetTuyen"].ToString() == "ĐẠT" &&
                ds.Tables["TUYENSINH"].Rows[bandedGridView1.FocusedRowHandle]["HanDangKy"] != DBNull.Value)))
            {
                MessageBox.Show("Thí sinh này không đạt hoặc đã đạt nhưng chưa có hạn đăng ký\nKhông in giấy tiếp nhận", "In giấy TN", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //In giay TN
            string strRptGBTN = "";
            try
            {
                switch (ds.Tables["TUYENSINH"].Rows[bandedGridView1.FocusedRowHandle]["MaKhoiDangKy"].ToString())
                {
                    case "01":
                    case "02":
                    case "03":
                    case "04":
                    case "05":
                        strRptGBTN = "sp_Print_GiayBaoTiepNhan_TieuHoc.rpt";
                        break;
                    case "06":
                    case "07":
                    case "08":
                    case "09":
                        strRptGBTN = "sp_Print_GiayBaoTiepNhan_THCS.rpt";
                        break;
                    case "10":
                    case "11":
                    case "12":
                        strRptGBTN = "sp_Print_GiayBaoTiepNhan.rpt";
                        break;
                }

                cmdInGBTN.Enabled = false;

                //Load report
                ReportDocument rpt = new ReportDocument();
                rpt.Load(Application.StartupPath + "\\Report\\" + strRptGBTN);

                //Set connection
                PublicFunction.SetDBLogonForReport(rpt);

                //Set parameter
                PublicFunction.SetParameter(rpt, "@pMaTuyenSinh", ds.Tables["TUYENSINH"].Rows[bandedGridView1.FocusedRowHandle]["MaTuyenSinh"].ToString());
                PublicFunction.SetParameter(rpt, "pMoRongDong", false);

                //View report
                frmPrintPreview frmPP = new frmPrintPreview(rpt);
                frmPP.ShowDialog();
                frmPP.Dispose();

                rpt.Dispose();
                cmdInGBTN.Enabled = true;

                //Doi trang thai
                ds.Tables["TUYENSINH"].Rows[bandedGridView1.FocusedRowHandle]["MaTrangThaiXetTuyen"] = "02";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bandedGridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
                ColumnView view = sender as ColumnView;
                string val_KQ = view.GetRowCellValue(e.RowHandle, view.Columns["MaKetQuaXetTuyen"]).ToString();
                string val_CoSoTiepNhan = view.GetRowCellValue(e.RowHandle, view.Columns["CoSoTiepNhan"]).ToString();
                if (val_KQ == "ĐẠT" || val_KQ == "THI ĐẠT")
                {
                    if (val_CoSoTiepNhan == "")
                    {
                        e.Valid = false;
                        e.ErrorText = "Chưa có cơ sở tiếp nhận";
                    }
                }
                //view.SetColumnError(gridColumn_CoSoTiepNhan, !e.Valid ? null : "Chưa có cơ sở tiếp nhận.", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Information);
        }

        
        private void bandedGridView1_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            //Suppress displaying the error message box
            e.ExceptionMode = ExceptionMode.NoAction;
            //Show the message with the error text specified 
            MessageBox.Show(e.ErrorText,"Duyet tuyen sinh", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        private void cmdDuKienTuyenSinh_Click(object sender, EventArgs e)
        {
            try
            {
                frmBaoCaoGiaoVu frmCR = new frmBaoCaoGiaoVu("Dự kiến tuyển sinh", Application.StartupPath + "\\Report\\Report_TuyenSinh_DuKienTuyenSinh.rpt");
                frmCR.strMaNienHoc =GlobalVariable.WSInfo.getAppProperty("MaNienHocMoi");
                frmCR.ShowDialog();
                frmCR.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Dự kiến tuyển sinh");
            }
        }

        private void cmdTinhHinhTuyenSinh_Click(object sender, EventArgs e)
        {
            try
            {
                frmBaoCaoGiaoVu frmCR = new frmBaoCaoGiaoVu("Thống kê tuyển sinh", Application.StartupPath + "\\Report\\Report_TuyenSinh_ThongKeTuyenSinh.rpt");
                frmCR.strMaNienHoc =GlobalVariable.WSInfo.getAppProperty("MaNienHocMoi");
                frmCR.ShowDialog();
                frmCR.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thổng kê tuyển sinh");
            }
        }

        private void splitContainerControl1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void grid_ThongTinXetTuyen_Click(object sender, EventArgs e)
        {

        }

        


    }
}
